package org.example.teachermanager.controller;

import org.example.teachermanager.entity.Teacher;
import org.example.teachermanager.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/list")
    public String teacher(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "12") int size,
            Model model
    ) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Teacher> teacherPage = teacherService.findAll(pageable);
        model.addAttribute("teachers", teacherPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", teacherPage.getTotalPages());
        return "/teacher/list";
    }

    @GetMapping("/findByNameLike")
    public String findTeacherByNameLike(
            @RequestParam String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "12") int size,
            Model model
    ) {
        name += '%'; // 添加通配符
        Pageable pageable = PageRequest.of(page, size);
        Page<Teacher> teacherPage = teacherService.findByNameLike(name, pageable);
        model.addAttribute("teachers", teacherPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", teacherPage.getTotalPages());
        model.addAttribute("searchName", name.trim());
        return "/teacher/list";
    }
}